package com.zhang.novel.core.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhang.novel.core.bean.UserDetails;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class JwtTokenUtil {

    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "created";

    @Value("${jwt.secret")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;

    /**
     * 从token中获取用户信息
     *
     * @param token
     * @return
     */
    public UserDetails getUserDetailsFormToken(String token) {
        // 先判断token是否有效
        if (isTokenExpired(token)) {
            return null;
        }
        // 从token获取信息
        UserDetails userDetails;
        try {
            Claims claims = getClaimsFormToken(token);
            userDetails = new ObjectMapper().readValue(claims.getSubject(), UserDetails.class);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            userDetails = null;
        }
        return userDetails;
    }

    /**
     * 从token中获取jwt的声明信息，如过期时间等
     *
     * @param token
     * @return
     */
    private Claims getClaimsFormToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.info("JWT格式验证失败：{}", token);
        }
        return claims;
    }

    /**
     * 判断token是否有效
     *
     * @param token
     * @return
     */
    private boolean isTokenExpired(String token) {
        // 获取token过期时间
        Date expiredDate = getExpiredDataFormToken(token);
        // 判断现在的时间是否在过期时间之前，是则有效，不是则无效
        return expiredDate.before(new Date());
    }

    /**
     * 获取token过期时间
     *
     * @param token
     * @return
     */
    private Date getExpiredDataFormToken(String token) {
        Claims claims = getClaimsFormToken(token);
        return claims.getExpiration();
    }

    /**
     * 根据用户信息生成token
     *
     * @param userDetails
     * @return
     */
    @SneakyThrows
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>(2);
        claims.put(CLAIM_KEY_USERNAME, new ObjectMapper().writeValueAsString(userDetails));
        claims.put(CLAIM_KEY_CREATED, new Date());

        return generateToken(claims);
    }

    /**
     * 根据声明信息生成token
     *
     * @param claims
     * @return
     */
    public String generateToken(Map<String,Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 生成token的过期时间
     *
     * @return
     */
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    /**
     * 判断token是否能够被刷新
     *
     * @param token
     * @return
     */
    public boolean canRefresh(String token) {
        return !isTokenExpired(token);
    }

    /**
     * 刷新token
     *
     * @param token
     * @return
     */
    public String refreshToken(String token) {
        Claims claims = getClaimsFormToken(token);
        claims.put(CLAIM_KEY_CREATED, new Date());

        return generateToken(claims);
    }
}
